import { useModel } from "@umijs/max"
import { App, Button, Card, DatePicker, Form, Input, Modal } from "antd"
import dayjs from "dayjs"
import React, { useState } from "react"

const DeviceLockModal: React.FC = () => {
  const { callPy } = useModel("websocketModel")
  const { deviceLockModalVisible, updateProduceData } = useModel("produceModel")
  const { message } = App.useApp()
  const [form] = Form.useForm()

  // 默认选择30天后的当前时间
  const defaultDateTime = dayjs().add(30, "day")
  const [selectedDateTime, setSelectedDateTime] = useState(defaultDateTime)

  const handleUnlock = async () => {
    try {
      const values = await form.validateFields()
      const args = [values.password, selectedDateTime.format("YYYY-MM-DD HH:mm:ss")]
      const response = await callPy("st", "unlock_device_from_web", args)
      if (response.state) {
        message.success("设备解锁成功")
        updateProduceData({ deviceLockModalVisible: false })
      } else {
        message.error("解锁失败: " + response.info, 5)
      }
    } catch (error) {
      console.log("验证失败:", error)
    }
  }

  const handleDateTimeChange = (date: dayjs.Dayjs | null) => {
    if (date) {
      setSelectedDateTime(date)
    }
  }

  return (
    <Modal
      title={
        <span style={{ color: "orange", fontSize: 16, fontWeight: "bold" }}>
          设备已锁定
        </span>
      }
      open={deviceLockModalVisible}
      width={600}
      style={{ top: 200 }}
      footer={null}
      closable={false}
      maskClosable={false}
    >
      <Card>
        <Form form={form} layout="vertical">
          <div style={{ textAlign: "center", marginBottom: 24 }}>
            <span
              style={{
                color: "#FF4D4F",
                fontSize: 16,
                fontWeight: 500,
                lineHeight: "24px"
              }}
            >
              设备已锁定，请输入激活码并选择下次锁定时间,默认是30天.
            </span>
          </div>

          <Form.Item
            name="password"
            label="激活码"
            rules={[{ required: true, message: "请输入激活码" }]}
          >
            <Input.Password placeholder="请输入激活码" />
          </Form.Item>

          <Form.Item
            name="expireDateTime"
            label="下次锁定时间"
            initialValue={defaultDateTime}
            rules={[{ required: true, message: "请选择锁定时间" }]}
          >
            <DatePicker
              showTime={{
                format: "HH:mm:ss",
                defaultValue: dayjs().endOf("day") // 默认设置为23:59:59
              }}
              style={{ width: "100%" }}
              format="YYYY-MM-DD HH:mm:ss"
              onChange={handleDateTimeChange}
            />
          </Form.Item>

          <Form.Item style={{ textAlign: "center", marginTop: 24 }}>
            <Button type="primary" onClick={handleUnlock}>
              解锁设备
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </Modal>
  )
}

export default () => (
  <App>
    <DeviceLockModal />
  </App>
)
